import decimal
import json
import math

from django.contrib.auth.decorators import login_required
from django.forms import model_to_dict
from django.http import HttpResponse, HttpResponseNotFound
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import generics, mixins, views
from rest_framework.pagination import PageNumberPagination
from rest_framework import permissions
from car.serializers import RecordListSerializer

from car.models import Record, Car


# Create your views here.
# @csrf_exempt
class AddCar(APIView):

    def post(self, request):
        """
        注册车辆
        """

        car_number = request.POST.get('car_number')
        name = request.POST.get('name')
        car, _ = Car.objects.get_or_create(car_number=car_number)
        car.name = name
        car.save()
        result = json.dumps({'code': 200})
        return HttpResponse(result)


# @csrf_exempt
class AddRecord(APIView):
    def post(self, request):
        """
        车辆进入，添加记录
        """
        print('22222', request.data)
        car_number = request.data.get('car_number')
        record = Record.objects.create(car_number=car_number)
        record.save()
        return Response({'code': 200})


def get_car_data(request):
    """
    获取车辆信息
    """
    car_number = request.GET.get('car_number')
    car = Car.objects.get(car_number=car_number)
    data = model_to_dict(car)
    result = json.dumps({'code': 200, 'data': data})
    return HttpResponse(result)


def get_car_record(request):
    """
    获取车辆的出入记录
    """
    car_number = request.GET.get('car_number')
    record_list = Record.objects.filter(car_number=car_number).order_by('-id').all()
    data_list = []
    for data in record_list:
        data_list.append(data.to_json())
    result = json.dumps({'code': 200, 'data': data_list})
    return HttpResponse(result)


def leave_place(request):
    """
    离开停车场

    1、更新离开时间
    2、收费金额
    :return:
    """
    # TODO 查看是否有进入记录
    record_id = json.loads(request.body).get('record_id')
    record = Record.objects.filter(id=record_id).last()
    if not record:
        result = json.dumps({'code': 400})
        return HttpResponse(result)

    # 计算离开时间以及消费金额
    start_time = record.in_time
    end_time = timezone.now()
    # 计算停留时间
    ctime = count_time(start_time, end_time)
    # 计算花费金额
    money = decimal.Decimal(cost_money(record.car_number, ctime))
    record.out_time = end_time
    record.money = money
    record.save()
    result = {
        'code': 200,
        'data': record.to_json()
    }
    result = json.dumps(result)
    return HttpResponse(result)


def cost_money(car_number, stay_time):
    """
    计算停车费用

    car_number: 车牌号
    stay_time: 停留时间 小时

    1、判断用户类型是否业主
    2、非业主，直接计算金额
    3、业主，判断是否包月、计算金额
    """
    stay_time = int(float(stay_time))
    car = Car.objects.filter(car_number=car_number).last()
    if not car:
        return 2 * stay_time

    if car.type == 1:
        return 0
    return 1 * stay_time


def count_time(start, end):
    """
    计算时间
    """
    seconds = (end - start).seconds
    hours = math.ceil(seconds / 3600)
    return hours


class LargeResultsSetPagination(PageNumberPagination):
    # 默认每页显示10条数据
    page_size = 10

    # 根据'page_size'关键字自定义每页显示多少条数据
    page_size_query_param = 'size'

    # 自定义'pag'关键字查询具体某一页的数据（默认为'page'）
    # 如：?pag=3 即查询第三页的数据
    page_query_param = 'page'

    # 每页最多显示15条数据
    # 克制 ?page_size=20,这样自定义无效，每页最多显示15条数据
    # max_page_size = 5


class RecordList(generics.RetrieveAPIView):
    """
    查看停车记录
    """
    permission_classes = [permissions.IsAuthenticated, ]
    serializer_class = RecordListSerializer

    pagination_class = LargeResultsSetPagination

    def get(self, request, *args, **kwargs):
        car_number = request.GET.get('car_number')
        record_list = Record.objects.filter(car_number=car_number).order_by('-id').all()
        total_count = record_list.count()

        # 实例化分页对象
        page_cursor = LargeResultsSetPagination()
        # 分页
        data_list = page_cursor.paginate_queryset(record_list, request, view=self)

        data_list = self.get_serializer(data_list, many=True).data
        result = {'code': 200, 'data': data_list, 'total_count': total_count}
        return Response(result)
